package com.rabbit.eap.controller.system;

import com.wf.captcha.SpecCaptcha;
import com.rabbit.eap.common.utils.UUIDUtil;
import com.rabbit.eap.config.constant.CommonRedisKey;
import com.rabbit.eap.framework.common.api.ApiResult;
import com.rabbit.eap.framework.common.constant.CommonConstant;
import com.rabbit.eap.framework.log.annotation.Module;
import com.rabbit.eap.framework.log.annotation.OperationLog;
import com.rabbit.eap.framework.log.enums.OperationLogType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @projectName eap
 * @packageName com.rabbit.eap.controller.system
 * @className CaptchaController
 * @author： rabbit
 * @version： 1.0
 * @since： 2020/5/31 20:10
 * <p>Description: CaptchaController
 * 验证码接口
 * </p>

 */
@Slf4j
@RestController
@Api(value = "验证码API", tags = {"验证码"})
@Module("system")
@RequestMapping("/captcha")
@ConditionalOnProperty(value = {"eap.enable-verify-code"}, matchIfMissing = true)
public class CaptchaController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/getCaptcha")
    @OperationLog(name = "获取验证码", type = OperationLogType.OTHER)
    @ApiOperation(value = "获取验证码", response = ApiResult.class)
    public ApiResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String verifyToken = UUIDUtil.getUuid();
        // 存入redis并设置过期时间为5分钟
        // 缓存到Redis
        redisTemplate.opsForValue()
                .set(String.format(CommonRedisKey.VERIFY_CODE, verifyToken), verCode, 5, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>(2);
        map.put(CommonConstant.IMAGE, specCaptcha.toBase64());
        map.put(CommonConstant.VERIFY_TOKEN, verifyToken);
        // 将key和base64返回给前端
        return ApiResult.ok(map);
    }
}
